package com.xxxx.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.xxxx.BeanLoad.RestBean;

public class MyBeanFactoryPostProcessor implements ApplicationContextAware,  BeanFactoryPostProcessor {  
	
	private static ApplicationContext applicationContext;  

	private String packageS;
	
    public String getPackageS() {
		return packageS;
	}

	public void setPackageS(String packageS) {
		this.packageS = packageS;
	}

	@Override  
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
    	MyBeanFactoryPostProcessor.applicationContext = applicationContext;  
    }  
  
    public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  
    public static Object getBean(String beanName) {  
        return applicationContext.getBean(beanName);  
    }  
      
    public static <T>T getBean(String beanName , Class<T>clazz) {  
        return applicationContext.getBean(beanName , clazz);  
    }  
	
    /**
	 * 此方法会在bean初始化完成但未实例化时调用
	 */
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)  
            throws BeansException {  
    	//beanFactory 也可以拿到当前系统从已经初始化好的bean,也可以做一些修改
    	//设置了扫描路径则则可以根据扫描包扫描相应的注解
    	System.out.println("packageS==================="+packageS);
    	//获取BeanFactory
    	DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
    	//模拟扫描到的bean,用动态代理等等方式创建    
    	//创建bean信息.
    	BeanDefinitionBuilder beanDefinitionBuilder =BeanDefinitionBuilder.genericBeanDefinition(RestBean.class);
    	beanDefinitionBuilder.addPropertyValue("name","张三");
    	//动态注册bean.
    	defaultListableBeanFactory.registerBeanDefinition("restBean",beanDefinitionBuilder.getBeanDefinition());
    	//注册进spring上下文的bean可以获取一下看看
    	BeanDefinition bd = beanFactory.getBeanDefinition("restBean");  
    } 
  
} 